﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Collections;

namespace DMSClient
{
    public partial class Unit : Form
    {
        
        DataSet ds = new DataSet();
        private DataTable dtUnit;
        int result = 0;
        string ambiente;
        EndpointAddress address;
        WSHttpBinding Binding = new WSHttpBinding();
        
        public Unit()
        {
            InitializeComponent();
            Binding = new WSHttpBinding();
            ambiente = Properties.Settings.Default.CurrentEnv;
            Binding.MaxReceivedMessageSize = 2147483647;
            Binding.MaxBufferPoolSize = 2147483647;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            address = new EndpointAddress(Properties.Settings.Default.Server);
           
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Unit";
        }

       
        private void Unit_Load(object sender, EventArgs e)
        {
            estado(false);



            ugUnits.DisplayLayout.Bands[0].Columns.Add("idUnit", "idUnit");

            ugUnits.DisplayLayout.Bands[0].Columns.Add("cdUnit", "cdUnit");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("nmUnit", "nmUnit");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("nmUnitShort", "nmUnitShort");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("idObjectType", "idObjectType");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("idStatus", "idStatus");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("cdUnitHist", "cdUnitHist");
            ugUnits.DisplayLayout.Bands[0].Columns.Add("flRemoteDelete", "flRemoteDelete");
            ugUnits.DisplayLayout.Bands[0].Columns["flRemoteDelete"].Hidden = true;
            ugUnits.DisplayLayout.Bands[0].Columns.Add("dtLastModified", "dtLastModified");
            ugUnits.DisplayLayout.Bands[0].Columns["dtLastModified"].Hidden = true;
            UnitWorker.RunWorkerAsync();
        }

        private void UnitWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string lista = "";

            try
            {
                client.Open();
                lista = client.listUnit(ambiente);
                client.Close();

                if (UnitWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
            if (lista == null)
            {
                throw new Exception("Error");
            }   


            dtUnit = new DataTable("Unitdt");
            dtUnit.Columns.Add("idUnit");
            dtUnit.Columns.Add("cdUnit");
            dtUnit.Columns.Add("nmUnit");
            dtUnit.Columns.Add("nmUnitShort");
            dtUnit.Columns.Add("idObjectType");
            dtUnit.Columns.Add("idStatus");
            dtUnit.Columns.Add("cdUnitHist");
            dtUnit.Columns.Add("flRemoteDelete");
            dtUnit.Columns.Add("dtLastModified");
            DataSet ds = new DataSet();
            ds.Tables.Add(dtUnit);

            System.IO.StringReader xmlSR = new System.IO.StringReader(lista);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);

            xmlSR.Close();
        }

        private void UnitWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugUnits.DataSource = dtUnit;
                estado(true);
            }
        }

        public void estado(bool estado)
        {
            loader.Visible = !estado;
            ultraGroupBox1.Enabled = estado;

        }

        private void ugUnits_BeforeCellActivate(object sender, Infragistics.Win.UltraWinGrid.CancelableCellEventArgs e)
        {
            if (e.Cell.Column.Index == 0)
            {
                e.Cancel = true;

            }
        }

        private void btNew_Click(object sender, EventArgs e)
        {
            ugUnits.Rows.Band.AddNew();
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugUnits.Rows)
            {                 
                /*VALIDANDO QUE LOS CAMPOS NO ESTEN VACIOS*/
                if (row.Cells["cdUnit"].Value.ToString().Equals(""))
                {
                    MessageBox.Show("The field cdUnit is clear!", "Unit");
                    return;
                }
                if (row.Cells["nmUnit"].Value.ToString().Equals(""))
                {
                    MessageBox.Show("The field nmUnit is clear!", "Unit");
                    return;
                }
            }
            
            estado(false);

            SaveWorker.RunWorkerAsync();
            
        }

        private void SaveWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string lista = "";
            
            List<Dtl.Unit> lisUnit = new List<Dtl.Unit>();
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugUnits.Rows)
            {
                Dtl.Unit unit = new Dtl.Unit();           
               

                if (row.Cells["idUnit"].Value.ToString().Equals("")) //Verifica que la columna idUnit esté vacia, en este caso se inserta un registo
                {
                    unit.typeOperation = 0;
                }
                else
                {
                    unit.typeOperation = 1;
                    unit.idUnit = int.Parse(row.Cells["idUnit"].Value.ToString());
                }

                unit.cdUnit = row.Cells["cdUnit"].Value.ToString();
                unit.nmUnit = row.Cells["nmUnit"].Value.ToString();
                unit.nmUnitShort = row.Cells["nmUnitShort"].Value.ToString();
                unit.idObjectType = row.Cells["idObjectType"].Value.ToString();
                unit.idStatus = row.Cells["idStatus"].Value.ToString();
                unit.cdUnitHist = row.Cells["cdUnitHist"].Value.ToString();
                lisUnit.Add(unit);
            }
            try
            {
                client.Open();
                if (client.SetTransactionUnit(lisUnit, ambiente))
                {
                    MessageBox.Show("Successfully saved record!", "Unit");

                }
                else
                {
                    MessageBox.Show("Error saving the record, please try again!", "Unit");
                }
                client.Close();
                if (SaveWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                } 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
            if (lista == null)
            {
                throw new Exception("Error");
            }
        }

        private void SaveWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                UnitWorker.RunWorkerAsync();
            }
        }

        private void ultraButton1_Click_1(object sender, EventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugUnits.Rows)
            {
                if (row.IsActiveRow && !row.Cells["idUnit"].Value.ToString().Equals(""))
                {
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    string caption = "Unit";
                    string mensaje = "Do You want to delete the record '" + row.Cells["idUnit"].Value.ToString() + "'?";
                    DialogResult resultado = MessageBox.Show(mensaje, caption, buttons);
                    

                    if(resultado == DialogResult.Yes)
                    {
                         MessageBox.Show(row.Cells["idUnit"].Value.ToString()); 
                         
                    }
                         
                }
            }
        }

        private void ultraButton2_Click(object sender, EventArgs e)
        {
                    
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    string caption = "Unit";
                    string mensaje = "Do You want to delete the record ?";
                    DialogResult resultado = MessageBox.Show(mensaje, caption, buttons);


                    if (resultado == DialogResult.Yes)
                    {
                        estado(false);
                        DeleteWorker.RunWorkerAsync();
                    }
        }

        private void DeleteWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            result = 0;
            client.Open();
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugUnits.Rows)
            {
                if (row.IsActiveRow)
                {
                    try
                    {
                        result = client.deleteUnit(int.Parse(row.Cells["idUnit"].Value.ToString()), ambiente);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message, ex.InnerException);
                    }
                   if (result == null)
                   {
                       throw new Exception("Error");
                   }
                }

            }
            client.Close();
        }

        private void DeleteWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                if (result == -1)
                {
                    estado(true);
                    MessageBox.Show("Successfully deleted record!", "Unit");

                }
                else
                {
                    estado(true);
                    MessageBox.Show("Error deleted the record, please try again!", "Unit");
                }
                UnitWorker.RunWorkerAsync();
            }
        }

    }
}
